package com.biluo.process.controller;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.biluo.common.result.Result;
import com.biluo.model.process.ProcessTemplate;
import com.biluo.process.service.OaProcessTemplateService;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 审批模板 前端控制器
 * </p>
 *
 * @author atguigu
 * @since 2023-02-14
 */
@RestController
@RequestMapping(value = "/admin/process/processTemplate")
@RequiredArgsConstructor
@Slf4j
public class OaProcessTemplateController {
	private final OaProcessTemplateService processTemplateService;

	// 分页查询审批模板
	@ApiOperation("获取分页审批模板数据")
	@GetMapping("{page}/{limit}")
	public Result<IPage<ProcessTemplate>> index(@PathVariable Long page,
												@PathVariable Long limit) {
		Page<ProcessTemplate> pageParam = new Page<>(page, limit);
		// 分页查询审批模板，把审批类型对应名称查询
		IPage<ProcessTemplate> pageModel = processTemplateService.selectPageProcessTempate(pageParam);
		return Result.ok(pageModel);
	}

	//@PreAuthorize("hasAuthority('bnt.processTemplate.list')")
	@ApiOperation(value = "获取")
	@GetMapping("get/{id}")
	public Result<ProcessTemplate> get(@PathVariable Long id) {
		ProcessTemplate processTemplate = processTemplateService.getById(id);
		return Result.ok(processTemplate);
	}

	//@PreAuthorize("hasAuthority('bnt.processTemplate.templateSet')")
	@ApiOperation(value = "新增")
	@PostMapping("save")
	public Result save(@RequestBody ProcessTemplate processTemplate) {
		processTemplateService.save(processTemplate);
		return Result.ok();
	}

	//@PreAuthorize("hasAuthority('bnt.processTemplate.templateSet')")
	@ApiOperation(value = "修改")
	@PutMapping("update")
	public Result updateById(@RequestBody ProcessTemplate processTemplate) {
		processTemplateService.updateById(processTemplate);
		return Result.ok();
	}

	//@PreAuthorize("hasAuthority('bnt.processTemplate.remove')")
	@ApiOperation(value = "删除")
	@DeleteMapping("remove/{id}")
	public Result remove(@PathVariable Long id) {
		processTemplateService.removeById(id);
		return Result.ok();
	}

	@ApiOperation(value = "上传流程定义")
	@PostMapping("/uploadProcessDefinition")
	public Result<Map<String, Object>> uploadProcessDefinition(MultipartFile file) throws FileNotFoundException {
		// 获取classes目录位置
		String path = new File(ResourceUtils.getURL("classpath:")
				.getPath()).getAbsolutePath();
		// 设置上传文件夹
		File tempFile = new File(path + File.separator + "processes");
		if (!tempFile.exists()) {
			boolean success = tempFile.mkdirs();
			if (!success) {
				log.error("创建目录失败，path: {}", tempFile.getPath());
			}
		}
		// 创建空文件，实现文件写入
		String filename = file.getOriginalFilename();
		File zipFile = new File(tempFile.getPath() + File.separator + filename);

		// 保存文件
		try {
			file.transferTo(zipFile);
		} catch (IOException e) {
			log.error("上传文件失败，path: {}, filename: {}", tempFile.getPath(), filename);
			return Result.fail();
		}

		Map<String, Object> map = new HashMap<>();
		// 根据上传地址后续部署流程定义，文件名称为流程定义的默认key
		map.put("processDefinitionPath", "processes" + File.separator + filename);
		map.put("processDefinitionKey", filename.substring(0, filename.lastIndexOf(".")));
		return Result.ok(map);
	}

	// 部署流程定义（发布）
	@ApiOperation(value = "发布")
	@GetMapping("/publish/{id}")
	public Result publish(@PathVariable Long id) {
		// 修改模板发布状态 1 已经发布
		// 流程定义部署
		processTemplateService.publish(id);
		return Result.ok();
	}

	public static void main(String[] args) {
		try {
			String path = new File(ResourceUtils.getURL("classpath:")
					.getPath()).getAbsolutePath();
			System.out.println(path);
		} catch (FileNotFoundException e) {
			throw new RuntimeException(e);
		}
	}

}

